package model.xml;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import model.dao.UserAccessDao;
import model.dao.UserDefaultDao;
import model.domain.UserDefaultBean;

public class XMLBuiler {
	public static void xmlMaker(String userId,String rootpath) throws Exception {
		ArrayList<UserDefaultBean> userdefaultbeanList = (ArrayList<UserDefaultBean>) UserDefaultDao.selectAllDefault();
		ArrayList<UserDefaultBean> useraccessbeanList = (ArrayList<UserDefaultBean>) UserAccessDao.selectJoinAccessAndDefault(userId);
		ArrayList<UserDefaultBean> newList = null; // 상위 두 리스트를 합성--> newList를 만든다

		Iterator<UserDefaultBean> iter = useraccessbeanList.iterator();
		while (iter.hasNext()) {
			newList.add(iter.next()); // 비어있는newList에 useraccessbeanList 채워놓음
		}

		System.out.println("완성되기 전 newList = " + newList);
		System.out.println("userdefaultbeanList = " + userdefaultbeanList);

		for (int i = 0; i < userdefaultbeanList.size(); i++) {
			if (!(newList.contains(userdefaultbeanList.get(i)))) {
				newList.add(userdefaultbeanList.get(i));
			}
		}
		System.out.println("합성된 완성 newList = " + newList);
		System.out.println("합성된 완성 newList size = " + newList.size()
									+ "=  userdefaultbeanList size = "+ userdefaultbeanList.size());
		// 여기까지는 다른 클래스로 분리시킬수 도 있다(나중에)

		// 본격 XML 파일 만들기
		Element ranking = new Element("RANKING");

		for (int i = 0; i < newList.size(); i++) {
			Element rank = new Element("RANK" + i + 1);
			ranking.addContent(rank);
			Element serviceId = new Element("SERVICEID");
			Element servicePUrl = new Element("PURL");
			Element serviceMUrl = new Element("MURL");

			rank.addContent(serviceId);
			rank.addContent(servicePUrl);
			rank.addContent(serviceMUrl);

			String serviceIdTEXT = newList.get(i).getServiceId();
			String servicePUrlTEXT = newList.get(i).getServicePUrl();
			String serviceMUrlTEXT = newList.get(i).getServiceMUrl();

			serviceId.setText(serviceIdTEXT);
			serviceId.setText(servicePUrlTEXT);
			serviceId.setText(serviceMUrlTEXT);
		}

		Document doc = new Document(ranking);
		XMLOutputter out = new XMLOutputter();
		Format f = out.getFormat();
		f.setEncoding("UTF-8");// 한글처리

		// 개행과 들여쓰기를 함께 해야함
		f.setLineSeparator("\n");// 개행
		f.setIndent("  ");// 들여쓰기
		f.setTextMode(Format.TextMode.TRIM);// Text에 의한 자동 줄바꿈해제
		FileWriter writer = null;
		try {
			writer = new FileWriter(rootpath+"/userXMLs/"+"rank_"+userId+".xml");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		out.setFormat(f); // 새로운 Format으로 설정
		try {
			// out.output(doc, System.out);
			out.output(doc, writer);// 파일 생성됨
		} catch (Exception e) {
			System.out.println("xml빌드 오류");
		} finally {
			writer.flush();
			writer.close();
		}
	}
}
